<template>
  <div class="content" ref="content">
    <SchemeList @getDetail="getDetail" @toEdit="toEdit" @toAdd="toAdd" />
    <div class="editorContent el-card">
      <div class="header">
        <div class="title">
          <h1>{{ schemeDetail.name }}</h1>
          <div class="schemeDetail">
            <div class="businessName">
              <el-icon> <Aim /> </el-icon>{{ schemeDetail.businessName }}
            </div>
            <div class="createdUser">
              <el-icon> <User /> </el-icon>{{ schemeDetail.createdUser }}
            </div>
            <div class="version">
              <el-icon> <Warning /> </el-icon>{{ schemeDetail.version }}
            </div>
            <div class="date">
              <el-icon> <Clock /> </el-icon>{{ schemeDetail.UpdatedAt }}
            </div>
          </div>
        </div>
        <div class="btn">
          <el-button size="mini" icon="Document" @click="download">
            下载
          </el-button>
          <el-button type="primary" size="mini" @click="toEdit">
            编辑
          </el-button>
        </div>
      </div>
      <div class="editorContentHtml">
        <div v-html="schemeDetail.doc" ref="doc" class="doc"></div>
        <div class="colum">
          <h2>目录</h2>
          <el-anchor
            :container="doc"
            direction="vertical"
            type="default"
            @click="handleClick"
          >
            <el-anchor-link
              :title="item.title"
              :key="index"
              v-for="(item, index) in catalog"
              :href="`#${item.id}`"
              :style="{ paddingLeft: (item.level - 1) * 14 + 'px' }"
            />
          </el-anchor>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
"use strict";
import { ref, onMounted, reactive, nextTick } from "vue";
import SchemeList from "./components/schemeList.vue";
import { tplDetail } from "./api/req.js";
import { useRouter } from "vue-router";
import moment from "moment";
import { emitter } from "@/utils/bus.js";
import htmlDocx from "html-docx-js/dist/html-docx.js";

const content = ref(null);
let catalog = reactive([]);
const doc = ref(null);
const schemeDetail = ref({});
const router = useRouter();
const itemId = ref("");

const getDetail = async (id) => {
  try {
    itemId.value = id;
    let res = await tplDetail({
      id,
    });
    if (res.code === 0) {
      res.data.UpdatedAt = moment(res.data.UpdatedAt).format(
        "YYYY-MM-DD hh:mm"
      );
      schemeDetail.value = res.data;
      getTitle();
    }
  } catch (error) {
    console.log(error);
  }
};

const handleClick = (e) => {
  e.preventDefault();
};

const download = async () => {
  // var a = document.createElement('a') // 生成一个a元素
  // var event = new MouseEvent('click') // 创建一个单击事件
  // a.href = '/report/document/Download?id=' + itemId.value; // 将生成的URL设置为a.href属性
  // a.dispatchEvent(event) // 触发a的单击事件
  // 获取 API 数据
  //   const response = await fetch(
  //     "/api/report/document/get?id=" + itemId.value
  //   );
  //   if (!response.ok) {
  //     throw new Error("Network response was not ok");
  //   }
  // 解析响应头中的 'Content-Disposition' 获取文件名
  //   const disposition = response.headers.get("Content-Disposition");
  //   let filename = "default_name.txt"; // 默认文件名，以防无法解析到文件名
  //   if (disposition && disposition.indexOf("attachment") !== -1) {
  //     const filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
  //     const matches = filenameRegex.exec(disposition);
  //     if (matches != null && matches[1]) {
  //       filename = decodeURIComponent(matches[1].replace("UTF-8''", "")); // 移除文件名周围的引号
  //     }
  //   }
  //   const blob = await response.blob();
  console.log("_response_", schemeDetail.value);
  let htmls = `<div style="text-align: center; font-size: 30px; margin-top: 50px">${schemeDetail.value.businessName}</div><div><img src=''/></div><div style="text-align: center; margin: 100px 0">
    <img src=""/>  
    </div><div style="text-align: center;margin-bottom: 20px;">杭州安恒信息技术股份有限公司</div>
      <div style="text-align: center;">${schemeDetail.value.UpdatedAt}</div>`
  let htmlDocxBlobs = await htmlDocx.asBlob(htmls+schemeDetail.value.doc);
  console.log("_htmlDocxBlobs_",htmlDocxBlobs)
    // 创建一个 URL 对象并为 Blob 指定一个 URL
    const url = URL.createObjectURL(htmlDocxBlobs);

    // 创建一个临时的 <a> 元素
    const a = document.createElement("a");
    a.style.display = "none";
    a.href = url;
    a.download = schemeDetail.value.businessName;

    // 将 <a> 元素添加到文档中
    document.body.appendChild(a);

    // 模拟点击 <a> 元素，触发下载
    a.click();


};

onMounted(() => {});
const historys = sessionStorage.getItem("historys");
console.log(JSON.parse(historys));

const isRouter = (name, query = {}) => {
  const index = JSON.parse(historys).findIndex((item) => item.name === name);
  if (index >= 0) {
    emitter.emit("switchTab", {
      name: "generation",
      query,
    });
  } else {
    router.push({
      path: "/layout/penetration/generation",
      query,
    });
  }
};
const toEdit = (id = itemId.value) => {
  isRouter("generation", {
    id,
  });
};

const toAdd = () => {
  isRouter("generation");
};

const getTitle = () => {
  nextTick(() => {
    // 根据之前设置的ref来获取文章的小标题
    const article_content = doc.value;
    // 想获取的标题，将想获取的小标题的标签添加到这
    const titleTag = ["H1", "H2", "H3", "H4", "H5", "H6"];
    article_content.childNodes.forEach((e, index) => {
      //具体执行步骤，比如：打印看看
      if (titleTag.includes(e.nodeName)) {
        const id = "header-" + index;
        // 设置元素id
        e.setAttribute("id", id);
        catalog.push({
          id: id,
          title: e.innerHTML,
          level: Number(e.nodeName.substring(1, 2)),
          nodeName: e.nodeName,
          //read：后期主要用来判断当前阅读的是哪一个小标题的内容
          read: false,
        });
      }
    });
  });
};
</script>

<style lang="scss" scoped>
.content {
  display: flex;
  height: 100%;
  background-color: #fff;

  .editorContent {
    flex: 1;
    display: flex;
    flex-direction: column;

    .editor {
      flex: 1;
      height: 100%;
      display: flex;
      flex-direction: column;
    }

    .header {
      display: flex;
      padding: 20px 10px;

      .title {
        flex: 1;
      }
    }

    .editorContentHtml {
      padding-left: 20px;
      display: flex;
      overflow: hidden;
      word-break: break-all;

      .doc {
        flex: 1;
        overflow-y: scroll;
        padding-right: 20px;

        p {
          margin-left: 40px;
        }
      }

      .colum {
        width: 200px;
      }
    }
  }

  .nav {
    line-height: 32px;
    padding: 0 10px;
    display: flex;
    justify-content: space-between;

    .save {
      img {
        vertical-align: text-top;
      }

      span {
        font-size: 14px;
        margin-left: 3px;
      }
    }
  }

  .title {
    .schemeDetail {
      display: flex;
      justify-content: space-between;
      font-size: 12px;
      color: rgb(120, 122, 125);
      height: 18px;
      line-height: 18px;

      .el-icon {
        margin-right: 5px;
      }

      div {
        width: 25%;
        display: flex;
        align-items: center;
      }
    }
  }

  .btn {
    display: flex;
    align-items: center;

    .el-button {
      height: 38px;
      width: 84px;
    }
  }
}
</style>
